<template>
  <div  v-loading="pageLoading">
    <div  class="time-select">
      <TimeSelect v-model:modelValue="state.time" @change="changeDate"/>
    </div>
    <CommonChart 
      class="chart-container-content"
      ref="commonChartRef"
      height="400px"
      width="1000px"
      :fullOptions="{
        options: option
      }"
      :loading="false"
      :id="`${config.id}-line-detail-chart`"
    />
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch, onUnmounted } from 'vue'
import CommonChart from '@/components/echarts/index.vue'
import TimeSelect from '@/components/time-select/index.vue'
import { errorHandling } from '@/api/error-handling';
import Worker from '@/hooks/worker/history-worker.js?worker';//
const props = defineProps({
  config: {
    type: Object,
    default: () => {}
  },
  visible: {
    type: Boolean,
    default: false
  },
  deviceId: {
    type: String,
    default: ''
  }
}) as {
  config: Record<string, any>,
  visible: boolean,
  deviceId: string
}
const state = reactive({
  time: 60
})
let option = {
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'time',
    show: false,
    axisLabel: {
      show: false
    },
    axisTick: {
      show: false
    }
  },
  grid:  {
    left: '50',right:'0', bottom:'10', height: '100%'
  },
  yAxis: {
    type: 'value',
    ...props.config.yAxis
  },
  series: [
    {
      type: 'line',
      showSymbol: false
    },
  ],
   visualMap: [
    {
      type: 'piecewise',
      show: false,
      dimension: 1,
      pieces: [{
        ...props.config.pieces,
        color: '#53bdf0' //超过部分的颜色
      }],
      outOfRange: { // 在选中范围外 的视觉元素，这里设置在正常范围内的图形颜色
        color: '#e0464c',
      }
    }
  ],
};

const worker = new Worker(); // 开启副线程
let start:any
const pageLoading = ref(false)
const getChartData = async() => {
  pageLoading.value = true
  await errorHandling(props.config.historyApi, {deviceId: props.deviceId, interval: state.time}, res => {
    const {
      firstTime,
      pointInterval,
      values
    } = res.data
    start = (new Date()).getTime()
    worker.postMessage({
      firstTime,
      pointInterval,
      values
    }); 
  })
  pageLoading.value = false
}
let  chartData: any[] = []
worker.onmessage = e => {
  chartData = e.data.data
  setOption()
  console.log((new Date()).getTime() - start)
}
const commonChartRef = ref()
const setOption = () => {
  commonChartRef.value?.setOption({
    series: [
      {
        data: chartData
      }
    ]
  });
}
const changeDate = () => {
  getChartData()
}
watch(() => props.visible, () => {
  props.visible && getChartData()
}, {
  immediate: true
})
onUnmounted(() => {
  worker.terminate();
})
</script>

<style lang="less" scoped>
.time-select {
  position: absolute;
  right: 51px;
  top: 16px;
}
</style>
